using AutoMapper;
using MediatR;
using RBAC.Domain.Dto.Output;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.Role;
using System.Linq;
using Microsoft.Extensions.Logging;
using RBAC.Domain.RBAC;

namespace RBAC.Read.Api.Application.Handler.Role
{
    public class GetRoleListHandler : IRequestHandler<GetRoleListCommand, APIPaging<GetRoleListDto>>
    {
        private readonly IBaseRepository<RoleModel> roleRepository;
        private readonly IBaseRepository<PermissionModel> permissionRepository;
        private readonly IBaseRepository<RolePermissionModel> rolePermissionRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetRoleListHandler> logger;

        public GetRoleListHandler(IBaseRepository<RoleModel> roleRepository, IBaseRepository<PermissionModel> permissionRepository, IBaseRepository<RolePermissionModel> rolePermissionRepository, IMapper mapper, ILogger<GetRoleListHandler> logger)
        {
            this.roleRepository = roleRepository;
            this.permissionRepository = permissionRepository;
            this.rolePermissionRepository = rolePermissionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIPaging<GetRoleListDto>> Handle(GetRoleListCommand request, CancellationToken cancellationToken)
        {
            APIPaging<GetRoleListDto> res = new APIPaging<GetRoleListDto>();
            
            try
            {
                logger.LogInformation("开始获取角色列表，页码: {PageIndex}, 页大小: {PageSize}", request.PageIndex, request.PageSize);
                
                // 构建查询条件
                string whereClause = "r.IsDeleted = false";
                object parameters = new { };
                
                if (!string.IsNullOrEmpty(request.RoleName))
                {
                    whereClause = "r.IsDeleted = false AND r.RoleName LIKE @RoleName";
                    parameters = new { RoleName = $"%{request.RoleName}%" };
                }

                // 使用多表联查一次性获取所有数据
                var multiTableSql = @"
                    SELECT 
                        r.Id,
                        r.RoleName,
                        r.CreateTime,
                        r.IsEnable,
                        rp.PermissionId,
                        p.PermissionName
                    FROM Role r
                    LEFT JOIN RolePermission rp ON r.Id = rp.RoleId AND rp.IsDeleted = false
                    LEFT JOIN Permission p ON rp.PermissionId = p.Id AND p.IsDeleted = false
                    WHERE " + whereClause + @"
                    ORDER BY r.Id, rp.PermissionId";
                
                logger.LogInformation("执行多表联查SQL: {Sql}", multiTableSql);
                if (!string.IsNullOrEmpty(request.RoleName))
                {
                    logger.LogInformation("查询参数: RoleName = {RoleName}", request.RoleName);
                }
                
                var allData = roleRepository.Query<dynamic>(multiTableSql, parameters);
                logger.LogInformation("查询到 {DataCount} 条原始数据", allData?.Count ?? 0);

                if (allData == null || !allData.Any())
                {
                    res.Code = APIEnums.Success;
                    res.PageDatas = new List<GetRoleListDto>();
                    res.TotalCount = 0;
                    res.Msg = "没有找到角色数据";
                    logger.LogInformation("没有找到角色数据");
                    return Task.FromResult(res);
                }

                // 按角色ID分组处理数据
                var roleGroups = allData
                    .GroupBy(item => (long)item.Id)
                    .ToList();

                logger.LogInformation("分组后得到 {GroupCount} 个角色", roleGroups.Count);

                var roleList = new List<GetRoleListDto>();
                
                foreach (var group in roleGroups)
                {
                    var roleId = group.Key;
                    var firstItem = group.First();
                    
                    // 提取角色基本信息
                    var roleName = (string)firstItem.RoleName;
                    var createTime = (DateTime)firstItem.CreateTime;
                    var isEnable = (bool)firstItem.IsEnable;
                    
                    // 提取权限信息
                    var permissionIds = new List<long>();
                    var permissionNames = new List<string>();
                    
                    foreach (var item in group)
                    {
                        // 只有当PermissionId不为null时才添加权限
                        if (item.PermissionId != null)
                        {
                            var permissionId = (long)item.PermissionId;
                            var permissionName = (string)item.PermissionName;
                            
                            // 避免重复添加
                            if (!permissionIds.Contains(permissionId))
                            {
                                permissionIds.Add(permissionId);
                                permissionNames.Add(permissionName);
                            }
                        }
                    }
                    
                    logger.LogInformation("角色 {RoleId} ({RoleName}) 权限数量: {PermissionCount}, 权限名称: [{PermissionNames}], 权限ID: [{PermissionIds}]", 
                        roleId, roleName, permissionNames.Count, 
                        string.Join(",", permissionNames), 
                        string.Join(",", permissionIds));
                    
                    var dto = new GetRoleListDto
                    {
                        Id = roleId,
                        RoleId = roleId,
                        RoleName = roleName,
                        CreateTime = createTime,
                        IsEnable = isEnable,
                        PermissionNames = permissionNames,
                        PermissionIds = permissionIds
                    };
                    
                    roleList.Add(dto);
                }

                // 按创建时间排序
                var orderedRoleList = roleList.OrderByDescending(x => x.CreateTime).ToList();

                // 分页处理
                var totalCount = orderedRoleList.Count;
                var pagedData = orderedRoleList
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToList();

                res.Code = APIEnums.Success;
                res.PageDatas = pagedData;
                res.TotalCount = totalCount;
                res.Msg = "获取角色列表成功";
                logger.LogInformation("获取角色列表成功，共 {Count} 个角色，当前页 {PageIndex}，页大小 {PageSize}", 
                    totalCount, request.PageIndex, request.PageSize);
                
                // 详细记录最终结果
                foreach (var role in pagedData)
                {
                    logger.LogInformation("最终角色数据: ID={Id}, 名称={RoleName}, 权限数量={PermissionCount}, 权限名称=[{PermissionNames}], 权限ID=[{PermissionIds}]", 
                        role.Id, role.RoleName, role.PermissionNames?.Count ?? 0,
                        string.Join(",", role.PermissionNames ?? new List<string>()),
                        string.Join(",", role.PermissionIds ?? new List<long>()));
                }
            }
            catch (Exception ex)
            {
                res.Code = APIEnums.Error;
                res.Msg = "获取角色列表失败";
                logger.LogError(ex, "获取角色列表失败: {Message}", ex.Message);
            }

            return Task.FromResult(res);
        }
    }
}
